package com.atguigu.gmall.auth.controller;

import com.atguigu.gmall.auth.service.AuthService;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/")
public class AuthController {
    @Resource
    AuthService authService;
    //登录成功后跳转会之前的页面
    @GetMapping("/toLogin.html")
    public String toLogin(@RequestParam(value = "returnUrl", //如果访问登录页时  携带了returnUrl登录成功跳转回去  如果没有跳转到首页
        defaultValue = "http://www.gmall.com") String returnUrl,
                          Model model){
        model.addAttribute("returnUrl",returnUrl);
        return "login";
    }
    //登录成功跳转会登录前的页面：使用重定向
    @ApiOperation("登录")
    @PostMapping("/login")
    public String login(@RequestParam("returnUrl")String returnUrl,
                        @RequestParam("loginName")String loginName,
                        @RequestParam("password")String password,
                        HttpServletRequest request,
                        HttpServletResponse response){
        //1,2,3: 登录、创建token、将token设置到响应报文中
        authService.login(loginName,password,request,response);
        //4、重定向回之前的页面
        return "redirect:"+returnUrl;
    }

}
